package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @version v1.0
 * @package com.itheima.controller
 * @description:
 * @author: Ewaits
 * @date: 2019/7/4 22:35
 */
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Reference
    private UserService userService;
    @Reference
    private MenuService menuService;
    @Reference
    private RoleService roleService;


    @RequestMapping("findMenu")
    public Result findMenu() {
        List<Integer> list = getRolesIds();
        List<Integer> meunIds = menuService.findMenuIds(list);
        try {
            List<Menu> menuList = menuService.findParentMenu(meunIds);

            List<Map> result = new ArrayList<>();
            for (Menu menu : menuList) {
                Map map = new HashMap();
                map.put("path", menu.getPath());
                map.put("title", menu.getName());
                map.put("icon", menu.getIcon());
                if (CollectionUtils.isEmpty(menu.getChildren())) {
                    map.put("children", menu.getChildren());
                } else {
                    map.put("children", getChildren(menu.getChildren()));
                }
                result.add(map);
            }


            return new Result(true, MessageConstant.GET_MENU_SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MENU_FAIL);
        }
    }

    private List<Integer> getRolesIds() {
        org.springframework.security.core.userdetails.User userDetail = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = userDetail.getUsername();
        User user = userService.findUserByUsername(username);
        Set<Role> roles = user.getRoles();
        List<Integer> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roles)) {
            roles.forEach(role -> {
                Integer roleId = role.getId();
                list.add(roleId);
            });
        }
        return list;
    }


    private List<Map> getChildren(List<Menu> children) {

        List<Map> list = new ArrayList<>();
        for (Menu child : children) {
            Map map = new HashMap();
            map.put("path", child.getPath());
            map.put("title", child.getName());
            map.put("linkUrl", child.getLinkUrl());
            if (CollectionUtils.isEmpty(child.getChildren())) {
                map.put("children", child.getChildren());
            } else {
                map.put("children", getChildren(child.getChildren()));
            }
            list.add(map);
        }
        return list;
    }


    @RequestMapping("findAllMenu")
    public Result findAll() {
        try {
            List<Menu> list = menuService.findAll();
            if (CollectionUtils.isEmpty(list)) {
                return new Result(false, "查询菜单失败");
            }
            return new Result(true, "查询菜单失败", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询菜单失败");
        }
    }

    @RequestMapping("findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return menuService.findPage(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
    }

    @RequestMapping("addMainMenu")
    public Result addMainMenu(@RequestBody Menu menu) {
        try {
            menuService.addMainMenu(menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加主菜单失败");
        }
        return new Result(true, "添加主菜单成功");
    }


    @RequestMapping("findMainMenuById")
    public Result findMainMenuById(Integer id) {
        try {
            Menu menu = menuService.findMainMenuById(id);
            if (ObjectUtils.isEmpty(menu)) {
                return new Result(false, "查询菜单失败");
            }
            return new Result(true, "查询菜单成功", menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询菜单失败");
        }
    }

    @RequestMapping("findThisChildrenMenuById")
    public Result findThisMenuById(Integer id) {
        try {
            List<Menu> list = menuService.findThisChildrenMenuById(id);
            return new Result(true, "查询子菜单成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询子菜单失败");
        }
    }

    @RequestMapping("editMainMenu")
    public Result edit(@RequestBody Menu menu) {
        try {
            menuService.edit(menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "编辑主菜单失败");
        }
        return new Result(true, "编辑主菜单成功");
    }

    @RequestMapping("deleteMainMenuById")
    public Result deleteMainMenuById(Integer id) {
        try {
            menuService.deleteMainMenuById(id);
        } catch (RuntimeException re) {
            re.printStackTrace();
            return new Result(false, re.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除主菜单失败");
        }
        return new Result(true, "删除主菜单成功");
    }

    @RequestMapping("addChildrenMenu")
    public Result addChildrenMenu(@RequestBody Menu menu, Integer parentId) {
        try {
            menuService.addChildrenMenu(menu, parentId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加子菜单失败");
        }
        return new Result(true, "添加子菜单成功");
    }

    @RequestMapping("findMenuByMenuId")
    public Result findMenuByMenuId(Integer id) {
        try {
            Menu menu = menuService.findMenuByMenuId(id);
            if (ObjectUtils.isEmpty(menu)) {
                return new Result(false, "菜单不存在");
            }
            return new Result(true, "查询菜单成功", menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询菜单失败");
        }
    }

    @RequestMapping("editMenu")
    public Result editMenu(@RequestBody Menu menu) {
        try {
            menuService.editMenu(menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "编辑菜单失败");
        }
        return new Result(true, "编辑菜单成功");
    }

    @RequestMapping("deleteMenuById")
    public Result deleteMenuById(Integer id) {
        try {
            menuService.deleteMenuById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
            return new Result(true, "删除成功");
    }

}
